//
//  QYMPresentationController.m
//
//
//  Created by LZ on 2018/3/8.
//  Copyright © 2018年 LZ. All rights reserved.
//

#import "QYMPresentationController.h"

@implementation QYMPresentationController

- (id)initWithPresentedViewController:(UIViewController *)presentedViewController
             presentingViewController:(UIViewController *)presentingViewController
                        contentHeight:(CGFloat)height
{
    self = [super initWithPresentedViewController:presentedViewController presentingViewController:presentingViewController];
    if (self) {
        
        self.contentHeight = height;
    }
    return self;
}


- (CGRect)frameOfPresentedViewInContainerView
{
    
    CGFloat height  = self.contentHeight;
    CGFloat originY = floor([UIScreen mainScreen].bounds.size.height-height);
    
    return CGRectMake(0, originY, [UIScreen mainScreen].bounds.size.width, height);
}

- (void)presentationTransitionWillBegin
{
    self.backView.alpha = 0.0;
    [self.containerView addSubview:self.backView];
    [self.containerView addSubview:self.buttonDisappear];
    
    
    [UIView animateWithDuration:0.3
                     animations:^{
                         self.backView.alpha = 1.0;
                     }];
}

- (void)presentationTransitionDidEnd:(BOOL)completed
{
    
}

- (void)dismissalTransitionWillBegin
{
    
    [UIView animateWithDuration:0.3
                     animations:^{
                         self.backView.alpha = 0.0;
                     }];
    
}

- (void)dismissalTransitionDidEnd:(BOOL)completed
{
    if (completed) {
        [self.backView removeFromSuperview];
        [self.buttonDisappear removeFromSuperview];
    }
}


#pragma mark -
- (UIView *)backView
{
    if (_backView == nil) {
        
        //NSLog(@"bounds:%@",NSStringFromCGRect(self.containerView.bounds));
        _backView = [[UIView alloc] initWithFrame:self.containerView.bounds];
        _backView.backgroundColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.7];
    }
    
    return _backView;
}

- (UIButton *)buttonDisappear
{
    if (_buttonDisappear == nil) {
        UIButton *button       = [UIButton buttonWithType:UIButtonTypeSystem];
        button.frame           = self.containerView.bounds;
        button.backgroundColor = [UIColor clearColor];
        [button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
        
        _buttonDisappear = button;
    }
    
    return _buttonDisappear;
}

- (void)buttonClicked:(UIButton *)button
{
    [self.presentedViewController dismissViewControllerAnimated:YES completion:nil];
}

@end

